<template>
	<view class="chat">
		<view class="nav_header">
			<u-navbar :title="title" @rightClick="rightClick" @leftClick="leftClick" custom-back="goback()">
				<view class="u-nav-slot" slot="right">
					<u-icon name="more-dot-fill" size="18" color="#252525"></u-icon>
				</view>
			</u-navbar>
		</view>

		<view class="container" :style="{ paddingTop: topHeight + 44 + 'px' }">
			<view class="wrap">
				<scroll-view scroll-y='true' class="scrollBox" refresher-enabled="true" :refresher-triggered="triggered"
					@refresherpulling="onPulling" @refresherrefresh="onRefresh" @refresherrestore="onRestore"
					@refresherabort="onAbort" style="height: 80vh;" :scroll-into-view="bottomId">
					<view v-for="(item, i) in msgList" :key="i" class="message-group">
						<view class="time-style clearfix tac" style="user-select: none;">
							<span>{{ formatTimestamp(item.createtime) }}</span>
						</view>
						<!-- 自己输入聊天消息 -->
						<view class="dis-flex flex-x-end flex-y-center" v-if="item.bySelf">
							<view class="imItem imBySelf" v-if="item.message_type == 'text'">{{ item.content }}</view>
							<view class="imItem imBySelf" v-else-if="item.message_type == 'share'"
								@click="toDetail(parseContent(item.content).id)">
								<template>
									<image v-if="parseContent(item.content).picture"
										:src="IMG_URL+parseContent(item.content).picture" class="picture"
										mode="widthFix" style="width: 400rpx;border-radius: 5%;" />
									<image v-else-if="parseContent(item.content).video_cover"
										:src="IMG_URL+parseContent(item.content).video_cover" class="picture"
										mode="widthFix" style="width: 400rpx;" />
									<image v-else src="/static/imgs/temp.png" class="imgs" mode="widthFix" />
									<view class="title" style="margin: 10rpx;">
										{{ parseContent(item.content).introduce }}</view>
									<view class="" style="display: flex;align-items: center;">
										<image :src="IMG_URL+parseContent(item.content).user_picture" mode="widthFix"
											style="width: 50rpx;border-radius: 50%;height:50rpx ;"></image>
										<view class="" style="margin-left: 10rpx;color: #888888;">
											{{ parseContent(item.content).username }}
										</view>
									</view>
								</template>
							</view>
							<view class="imItem imBySelf" v-else style="width: 54%;">
								<ImContent :content="item.content" :bySelf="item.bySelf" :type="item.message_type"
									:userid="item.user.id" :messageid="parseInt(item.id, 10)" :shipid="item.ship_id">
								</ImContent>
							</view>
							<image v-if="item.user.avatar" class="avatar" :src="IMG_URL + item.user.avatar"
								style="border-radius:50%;height: 80rpx;" />
							<image v-else class="avatar" src="/static/imgs/tou.png" mode="widthFix" />
						</view>

						<view class="dis-flex flex-x-start flex-y-center" v-if="!item.bySelf">
							<image v-if="item.user.avatar" class="avatar" :src="IMG_URL + item.user.avatar"
								style="border-radius:50%;height: 80rpx;" />
							<image v-else class="avatar" src="/static/imgs/tou.png" mode="widthFix" />

							<view class="imItem" v-if="item.message_type == 'text'">{{ item.content }}</view>
							<view class="imItem share" v-else-if="item.message_type == 'share'"
								@click="toDetail(parseContent(item.content).id)">
								<template>

									<image v-if="parseContent(item.content).picture"
										:src="IMG_URL+parseContent(item.content).picture" class="picture"
										mode="widthFix" style="width: 400rpx;border-radius: 5%;" />
									<image v-else-if="parseContent(item.content).video_cover"
										:src="IMG_URL+parseContent(item.content).video_cover" class="picture"
										mode="widthFix" style="width: 400rpx;" />
									<image v-else src="/static/imgs/temp.png" class="imgs" mode="widthFix" />
									<view class="title" style="margin: 10rpx;">
										{{ parseContent(item.content).introduce }}</view>
									<view class="" style="display: flex;align-items: center;">
										<image :src="IMG_URL+parseContent(item.content).user_picture" mode="widthFix"
											style="width: 50rpx;border-radius: 50%;height:50rpx ;"></image>
										<view class="" style="margin-left: 10rpx;color: #888888;">
											{{ parseContent(item.content).username }}
										</view>
									</view>
								</template>
							</view>
							<view class="imItem " v-else style="width: 54%;">
								<ImContent :content="item.content" :bySelf="item.bySelf" :type="item.message_type"
									:userid="item.user.id" :messageid="parseInt(item.id, 10)" :shipid="item.ship_id">
								</ImContent>
							</view>
						</view>

					</view>
					<view :id="'p' + (msgList.length)"></view>
				</scroll-view>
			</view>

		</view>
		<view class="footer" ref="messfoot">
			<u-input placeholder="说点什么..." shape="circle" v-model="content">
				<template slot="suffix">
					<text class="send" @click="sendChat()">发送</text>
				</template>
			</u-input>
		</view>
		<view class="address-window" :class="selected == true ? 'on' : ''">
			<view class="wrap">
				<view class="del" @click="onDeleteChat()">删除对话</view>
			</view>
		</view>
		<view class='mask' catchtouchmove="true" :hidden='selected == false' @click='close'></view>
	</view>
</template>

<script>
	import {
		msgList,
		sendMessage,
		delList
	} from '@/api/chat.js';
	import {
		IMG_URL,
	} from "../../config/app.js";
	import UniNavBar from "@/components/uniNavbar/index.vue"
	import ImContent from "@/components/imcontent.vue"
	import ChatSign from '@/components/chatSign'
	import {
		getUserInfo,
	} from "../../api/login.js";
	import {
		signAgreement,
		delFriend
	} from "../../api/my.js";
	export default {
		name: 'chat', // 聊天
		components: {
			UniNavBar,
			ImContent,
			ChatSign
		},
		data() {
			return {
				IMG_URL: IMG_URL,
				title: '',
				msgList: [],
				paginate: 20,
				user: {},
				content: "",
				currentPage: 1,
				// triggered: true,
				conversation_id: '',
				isSign: false,
				triggered: true,
				scrollId: '',
				bottomId: 'p20',
				me: '',
				sign: '',
				selected: false,
			}
		},
		onLoad(option) {
			let data = JSON.parse(option.data)
			console.log(data, '获取数据');
			this.conversation_id = data.conversation_id
			this.msgLists(this.conversation_id)
			this.title = data.user_id.username
			this.user = data.user_id
			console.log(this.user);
			this._freshing = false;
			// this.getData()
			//滚动到最底部
			setTimeout(() => {
				this.num = this.msgList.length
				this.bottomId = 'p' + (this.num)
				console.log(this.bottomId, '接受聊天记录长度');
			}, 200)
		},
		created() {

		},
		onShow() {
			// 接收消息
			this.$socket.getMessage(res => {
				let data = JSON.parse(res.data);
				console.log(data, '0909090');
				if (data.type == "sendMessage") {
					console.log('---------', data.type);
					let message = {
						'bySelf': false,
						'content': data.data.content,
						'createtime': data.data.time,
						'message_type': data.data.message_type,
						'id': data.data.id,
						'user': this.user,
						'me': this.me,
						'ship_id': data.data.ship_id,
						// 'notice':data.data.notice
					}
					this.msgList.push(message)
					setTimeout(() => {
						this.num = this.msgList.length
						this.bottomId = 'p' + (this.num)
					}, 200)
				}
			})
		},
		mounted() {

		},
		methods: {
			toSelect() {
				this.selected = true
			},
			toDetail(id) {
				uni.navigateTo({
					url: '/pages/hall/hallDetails?id=' + id
				})
			},
			parseContent(content) {
				return JSON.parse(content);
			},
			async getData() {
				let res = await signAgreement({

				}).then(res => {
					console.log(res, '是否签署协议');

				});
			},
			formatTimestamp(timestamp) {
				const date = new Date(timestamp * 1000);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const seconds = date.getSeconds().toString().padStart(2, '0');

				const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
				return formattedDate;
			},
			onPulling(e) {
				console.log("onpulling", e);
			},
			onRestore() {
				this.triggered = 'restore'; // 需要重置
				console.log("onRestore");
			},
			onAbort() {
				console.log("onAbort");
			},
			onRefresh() {
				if (this._freshing) return;
				this._freshing = true;
				setTimeout(() => {
					this.msgLists(this.conversation_id)
					this.triggered = false;
					this._freshing = false;
				}, 1500)
			},
			//删除会话
			async onDeleteChat() {
				await delList({
					'conversation_id': this.conversation_id,
				}).then(res => {
					uni.showToast({
						'title': res.msg,
						'icon': 'none',
						'duration': 1000
					})
					if(res.code == 1){
						this.selected = false
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					}
				})
			
			},
			rightClick() {
				console.log('保存')
				this.selected = true
			},
			// 返回
			leftClick() {
				uni.navigateBack()
			},
			goback() {
				uni.navigateBack()
			},
			async msgLists(conversation_id) {
				console.log(conversation_id);
				const res = await msgList({
					'conversation_id': conversation_id,
					'paginate': this.paginate,
					'page': this.currentPage
				}).then(res => {
					console.log(res, '获取聊天漫游');
					let newData = this.sortedMessages(res.data.data)
					// 如果是加载更多，则再前面追加数据
					if (this.currentPage > 1) {
						this.msgList = newData.concat(this.msgList);
					} else {
						// 如果是刷新或第一次加载，直接替换消息列表
						this.msgList = newData;
					}
					if (this.currentPage !== 1) {
						// 判断是否是最后一页
						if (this.currentPage > res.data.last_page) {
							this.triggered = false

							uni.showToast({
								'title': '没有更多记录了',
								'icon': 'none',
								'duration': 1000
							})
						}

					}
					this.currentPage++
					setTimeout(() => {
						this.num = this.msgList.length
						this.bottomId = 'p' + (this.num)
						console.log(this.bottomId, '获取聊天记录长度');
					}, 200)
				});
			},
			//发送消息
			async sendChat() {
				const res = await sendMessage({
					'messageType': 'text',
					'user_id': this.user.id,
					'content': this.content
				}).then(res => {

					console.log(res, '发送消息');
					if (res.code == 1) {
						this.msgList.push(res.data)
						this.content = ''
						setTimeout(() => {
							this.num = this.msgList.length
							this.bottomId = 'p' + (this.num)
						}, 200)

					} else {
						uni.showToast({
							'duration': 1500,
							'icon': 'none',
							'title': res.msg
						})
					}
				});
			},
			//排序数据
			sortedMessages(messages) {
				return messages.sort((a, b) => a.createtime - b.createtime);
			},
		}
	}
</script>
<style lang="scss">
	page {
		background-color: #f6f6f6;
	}
</style>
<style lang="scss" scoped>
	.chat {
		height: 100%;
		width: 100vw;

		.nav_header {
			position: fixed;
			left: 0;
			right: 0;
			top: 0;
			z-index: 9999;
			background-color: #fff;
			height: 100rpx;
		}

		.container {
			height: calc(100vh - 100rpx-100rpx);

			.wrap {
				background: #fff;
				padding: 0 30rpx;
				height: calc(100vh - 120rpx - 88rpx);

				.scrollBox {
					height: 100%;

					.message-group {
						clear: both;
						overflow: hidden;
					}

					.time-style {
						font-size: 24rpx;
						color: #999;
						padding: 40rpx 0;
					}

					.avatar {
						width: 78rpx;
					}

					.imItem {

						background: #F6F6F6;
						border-radius: 14rpx 0px 14rpx 14rpx;
						padding: 18rpx 20rpx;
						font-size: 28rpx;
						color: $uni-text-color;
						margin: 0 20rpx;
						word-wrap: break-word;
						word-break: break-all;
					}

					.imBySelf {
						// margin-left: 0;
						margin: 0 20rpx;
						background: $uni-text-color;
						color: #FFFEFE;
					}
				}
			}


		}

		.footer {
			padding: 20rpx 30rpx;
			height: 120rpx;
			z-index: 999;
			background-color: #F6F6F6;
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;

			.send {
				color: $uni-text-color;
			}

			/deep/ .u-input {
				background: #fff;
			}
		}
	}

	.share {}

	.title {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		overflow: hidden;
		/* 设置要显示的行数 */
		-webkit-line-clamp: 2;
		/* 这里设置为 2 表示最多显示两行 */
	}

	.address-window {

		background: #F6F6F6;
		box-shadow: 0px 0px 30rpx 0px rgba(202, 202, 202, 0.6);
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		z-index: 99999;
		transform: translate3d(0, 100%, 0);
		transition: all .3s cubic-bezier(.25, .5, .5, .9);
		border-radius: 30rpx 30rpx 0 0;
		padding: 40rpx 30rpx 100rpx;

		&.on {
			transform: translate3d(0, 0, 0);
		}

		.wrap {
			padding: 0 30rpx;
			background: #fff;

			.toTalk {
				padding: 35rpx 0;
				border-bottom: 1px solid #eee;
				font-size: 30rpx;
				color: $uni-text-color;
			}

			.del {
				font-size: 30rpx;
				color: #FE3849;
				padding: 35rpx 0;
			}
		}
	}
</style>